<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use think\Db;
use app\common\model\Company as CompanyModel;
use app\common\model\Act as ActModel;
use app\common\model\Recharge as RechargeModel;
use app\common\model\Gather as GatherModel;
use app\common\model\Gatherreg as GatherregModel;
use app\common\model\Renzhensiyuan as RenzhensiyuanModel;
use app\common\model\Ilike as IlikeModel;
use app\common\model\News as NewsModel;
use app\common\model\ActsOrder as ActsOrderModel;

/**
 * 寺院控制器
 * Class Company
 * @package app\home\controller
 */
class Company extends Base
{
    /**
     * [getHomeCom  首页展示最新的寺院]
     * @param
     * @author [C。]
     * @return json
     */
    public function getHomeCom()
    {
        $model = new CompanyModel;
        $cmodel = new IlikeModel();
        $param = input('param.');
        $map = [];
        try{
//            $data = $this->redis->get($_SERVER['SERVER_NAME'].'hcompanyhomecom');
//            if(!$data){
                $map['states'] = 1;
                $map['info|istop'] = 1;
                $data = $model->getCompanyByConditons($map,0,2);
                $member = $this->getMember($param['token']);
                foreach($data as $k=>$v){
                    $focus = $cmodel->getAllCount(['status'=>1,'itemid'=>$v['id']]);
                    $data[$k]['focusnum'] = $v['focus'] + $focus;
                    $http = substr($v['compic'],0,4);
                    if($http != 'http'){
                        $data[$k]['compic'] = config('domain_name').$v['compic'];
                    }
                    $map1 = array(
                        'itemid' => $v['id'],
                        'memid' => $member['id']
                    );
                    $focus = $cmodel->findDataByComid($map1);
                    if(!empty($focus) && $focus['status'] == 1){
                        $data[$k]['focus'] = 1;
                    }else{
                        $data[$k]['focus'] = 0;
                    }
                }
//                $this->redis->set($_SERVER['SERVER_NAME'].'hcompanyhomecom',$data,360);
//            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }

    /**
     * [getIndex  古刹列表]
     * @param
     * @author [C。]
     * @return json
     */
    public function getIndex()
    {
        $model = new CompanyModel;
        $cmodel = new IlikeModel();
        $param = input('param.');
        $this->getPageAndSize($param);
        $map = [];
        if (is_array($param)) {
            if (!empty($param['province']))
                $map['province'] = $param['province'];
            if (!empty($param['city']))
                $map['city'] = $param['city'];
            if (!empty($param['qu']))
                $map['qu'] = $param['qu'];
        }
        try{
            $map['states'] = 1;
            $map['is_show'] = 1;
            $count = $model->getCompanyCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getCompanyByConditons($map,$this->from, $this->size,'',2);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        $member = $this->getMember($param['token']);
        foreach($lists as $k=>$v){
            $focus = $cmodel->getAllCount(['status'=>1,'itemid'=>$v['id']]);
            $lists[$k]['focusnum'] = $v['focus'] + $focus;
            $map1 = array(
                'itemid' => $v['id'],
                'memid' => $member['id']
            );
            $focus = $cmodel->findDataByComid($map1);
            if(!empty($focus) && $focus['status'] == 1){
                $lists[$k]['focus'] = 1;
            }else{
                $lists[$k]['focus'] = 0;
            }
            $http = substr($v['compic'],0,4);
            if($http != 'http'){
                $lists[$k]['compic'] = config('domain_name').$v['compic'];
            }
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getIndex  根据id获取古刹]
     * @param
     * @author [C。]
     * @return json
     */
    public function getFind()
    {
        $model = new CompanyModel;
        $amodel = new ActModel();
        $rmodel = new RechargeModel();
        $gmodel = new GatherModel();
        $grmodel = new GatherregModel();
        $cmodel = new IlikeModel();
        $omodel = new ActsOrderModel;
        $param = input('param.');
        $member = $this->user;
        try{
            $model->edit_readnum(['id'=>$param['id']]);
            $res = get_config();
            $company = $model->findData($param['id'],'id','id,comname,compic,title,phone,addr,city,qu,lng,lat,imgs,focus,jieyuan_isshow');
            if($res['jie_yuan_is_show'] == 0){
                $company['jieyuan_isshow'] = 0;
            }

            $http = substr($company['compic'],0,4);
            if($http != 'http'){
                $company['compic'] = config('domain_name').$company['compic'];
            }
            if(!empty($company['imgs'])){
                $company['imgs'] = explode(',',$company['imgs']);
            }else{
                $company['imgs'] = explode(',',$company['compic']);
            }

            $focus = $cmodel->getAllCount(['status'=>1,'itemid'=>$company['id']]);

            $company['focusnum'] = $company['focus'] + $focus;
            if(!empty($member)){
                $map1 = array(
                    'itemid' => $company['id'],
                    'memid' => $member['id']
                );

                $focus = $cmodel->findDataByComid($map1);
                if(!empty($focus) && $focus['status'] == 1){
                    $company['focus'] = 1;
                }else{
                    $company['focus'] = 0;
                }
            }
            $act = $amodel->findOne(['comid'=>$param['id'],'states'=>1],'id,title,cover,amount');

            if(!empty($act)){
                $http = substr($act['cover'],0,4);
                if($http != 'http'){
                    $act['cover'] = config('domain_name').$act['cover'];
                }
                $count = $rmodel->getRechargeCount(['item_id'=>$act['id'],'states'=>1]);
                $count1 = $omodel->getRechargeCount(['aid'=>$act['id']]);
                $hasamount = $rmodel->getAlreadyRaising($act['id']);
                $hasamount1 = $omodel->getAlreadyRaising($act['id']);
                $act['love'] = $count + $count1;
                $act['jindu'] = round($hasamount + $hasamount1/$act['amount'] * 100,2).'%';
                $act['amount'] = round($act['amount'],2);
                $act['hasraising'] = round($hasamount + $hasamount1,2);
            }


            $gather = $gmodel->getWorker(['comid'=>$param['id'],'type'=>2,'states'=>1],'id,title,maxnum,cover,intro,starttime,endtime,comid,num,activetime');
            foreach($gather as $k=>$v){
                $http = substr($v['cover'],0,4);
                if($http != 'http'){
                    $gather[$k]['cover'] = config('domain_name').$v['cover'];
                }
                if($v['starttime'] <= time() && time() <= $v['endtime']){
                    $gather[$k]['state'] = '报名中';
                }
                if(time() > $v['endtime']){
                    $gather[$k]['state'] = '已结束';
                }
                $gather[$k]['starttime'] = date('Y-m-d',$v['starttime']);
                $gather[$k]['endtime'] = date('Y-m-d',$v['endtime']);
                $gather[$k]['activetime'] = date('Y-m-d',$v['activetime']);
                $hasnum = $grmodel->getCount(['gather_id'=>$v['id']]);
                $gather[$k]['hasnum'] = $hasnum + $v['num'];
                if($v['maxnum'] <= $gather[$k]['hasnum']){
                    $gather[$k]['state'] = '已完成';
                }
            }

            $active = $gmodel->getWorker(['comid'=>$param['id'],'type'=>1,'states'=>1],'id,title,maxnum,cover,intro,starttime,endtime,comid,num,activetime');
            foreach($active as $k=>$v){
                $http = substr($v['cover'],0,4);
                if($http != 'http'){
                    $active[$k]['cover'] = config('domain_name').$v['cover'];
                }
                if($v['starttime'] <= time() && time() <= $v['endtime']){
                    $active[$k]['state'] = '报名中';
                }
                if(time() > $v['endtime']){
                    $active[$k]['state'] = '已结束';
                }
                $active[$k]['starttime'] = date('Y-m-d',$v['starttime']);
                $active[$k]['endtime'] = date('Y-m-d',$v['endtime']);
                $active[$k]['activetime'] = date('Y-m-d',$v['activetime']);
                $ahasnum = $grmodel->getCount(['gather_id'=>$v['id']]);
                $active[$k]['hasnum'] = $ahasnum + $v['num'];
                if($v['maxnum'] <= $active[$k]['hasnum']){
                    $active[$k]['state'] = '已完成';
                }
            }
            if(!empty($member)){
                add_quality($member['id'],23,$member['quality'],3);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }

        $data = array(
            'temple'=>$company,
            'donation'=>$act,
            'gather'=>$gather,
            'active'=>$active
        );
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [getContent  根据id获取古刹内容]
     * @param
     * @author [C。]
     * @return json
     */
    public function getContent()
    {
        $model = new CompanyModel;
        $param = input('param.');
        try{
            $company = $model->findData($param['id'],'id','content,lng,lat,focus');
            $imodel = new IlikeModel();
            $focus = $imodel->getAllCount(['status'=>1,'itemid'=>$param['id']]);
            $company['focus'] = $company['focus'] + $focus;
//            preg_match_all('/src="Public\/kindeditor\/attached\/image\/(.*?(jpg|jpeg|gif|png))/', percent($company['content']), $url);
            $company['content'] = get_img_thumb_url(percent($company['content']),config('domain_name').'/');
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$company);
    }
    /**
     * [getAct  根据寺院id获取乐善好施]
     * @param
     * @author [C。]
     * @return json
     */
    public function getAct()
    {
        $model = new ActModel;
        $rmodel = new RechargeModel();
        $param = input('param.');
        $this->getPageAndSize($param);
        $map = [];
        try{
            $map['comid'] = $param['id'];
            $map['states'] = 1;
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map,$this->from, $this->size,'id,title,cover,amount');
            foreach($lists as $k=>$v){
                $http = substr($v['cover'],0,4);
                if($http != 'http'){
                    $lists[$k]['cover'] = config('domain_name').$v['cover'];
                }
                $count = $rmodel->getRechargeCount(['item_id'=>$v['id'],'states'=>1]);
                $hasamount = $rmodel->getAlreadyRaising($v['id']);
                if($hasamount >= $v['amount']){
                    $lists[$k]['isstop'] = 1;
                }else{
                    $lists[$k]['isstop'] = 0;
                }
                $lists[$k]['love'] = $count;
                $lists[$k]['jindu'] = round($hasamount/$v['amount'] * 100,2).'%';
                $lists[$k]['amount'] = round($v['amount'],2);
                $lists[$k]['hasraising'] = round($hasamount,2);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [postAdd  寺院入住]
     * @param
     * @return json
     * @author [C。]
     */
    public function postAdd()
    {
        $param = input('param.');
        $mem = $this->getMember($param['token']);
        $rmodel = new RenzhensiyuanModel();

        try{
            $param['addtime'] = time();
            $param['uid'] = $mem['id'];
            $id = $rmodel->addData($param);
        }catch (\Exception $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1,'添加失败'.$e->getMessage());
        }

        return admin_json(1, '添加成功',$id);
    }
    /**
     * [postAdd  申请明细]
     * @param
     * @return json
     * @author [C。]
     */
    public function getList()
    {
        $param = input('param.');
        $mem = $this->getMember($param['token']);
        $rmodel = new RenzhensiyuanModel();
        $this->getPageAndSize($param);
        $map = [];
        try{
            $map['uid'] = $mem['id'];
            $count = $rmodel->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $rmodel->getlist($map,$this->from, $this->size);

            foreach($lists as $k=>$v){
                $lists[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            }
        }catch (\Exception $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1,'获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getOne  根据id查找一条申请明细]
     * @param
     * @return json
     * @author [C。]
     */
    public function getOne()
    {
        $param = input('param.');
        $model = new RenzhensiyuanModel;
        try{
            $company = $model->findData($param['id']);
        }catch (\Exception $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1,'获取失败'.$e->getMessage());
        }
        return admin_json(1,'获取成功',$company);
    }
    /**
     * [postFocus  关注]
     * @param
     * @return json
     * @author [C。]
     */
    public function postFocus()
    {
        $param = input('param.');
        $model = new IlikeModel();
        $mem = $this->getMember($param['token']);
        try{
            $like = $model->findDataByComid(['memid'=>$mem['id'],'itemid'=>$param['id']]);
            if(empty($like)){
                $msg = '关注成功';
                $model->addData(['memid'=>$mem['id'],'itemid'=>$param['id'],'addtime'=>time()]);
            }else{
                if($like['status'] == 1){
                    $status = 0;
                    $msg = '取消关注成功';
                }else{
                    $status = 1;
                    $msg = '关注成功';
//                    add_quality($mem['id'],24,$mem['quality'],3);
                }
                $model->editData(['status'=>$status,'id'=>$like['id']]);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '关注失败'.$e->getMessage());
        }

        return admin_json(1, $msg);
    }
    /**
     * [getRecommend  获取推荐文章]
     * @param
     * @return json
     * @author [C。]
     */
    public function getRecommend()
    {
        $model = new NewsModel();
        $map = [];
        try{
            $map['states'] = 1;
            $map['recommend1'] = 1;
            $list = $model->getlists($map,0,3);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$list);
    }
    /**
     * [getMyFocus  我关注的寺院]
     * @param
     * @return json
     * @author [C。]
     */
    public function getMyFocus()
    {
        $param = input('param.');
        $model = new IlikeModel();
        $mem = $this->getMember($param['token']);
        $this->getPageAndSize($param);
        $map = [];
        try{
            $map['i.memid'] = $mem['id'];
            $map['i.status'] = 1;
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map,$this->from, $this->size,'i.id,c.id comid,c.compic,c.comname,c.province,c.city,c.qu,c.lng,c.lat');
            foreach($lists as $k=>$v){
                $http = substr($v['compic'],0,4);
                if($http != 'http'){
                    $lists[$k]['compic'] = config('domain_name').$v['compic'];
                }
                $lists[$k]['focus'] = 1;
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getLoginRecord  添加寺院登录记录]
     * @author [C。]
     * @return json
     */
    public function getLoginRecord()
    {
        $param = input('param.');
        $mem = $this->user;
        //判断会话是否过期
        if (time() - $mem['tokentime'] > config('home.token_expire')) {
            $token = md5('app' . $mem['tel'] . config('home.token_halt').time());
            Db::name('member')->where('id',$mem['id'])->update(['token'=>$token,'tokentime'=>time()]);
        }else{
            $token = $mem['token'];
        }
        $day = strtotime(date('Y-m-d'));
        $sday = $day - 3600*24*7;
        if($mem['addtime'] < $sday){
            return admin_json(1,'用户注册时间已经超过7天',['token'=>$token]);
        }

        $record = Db::name('login_record_son')->where(['memid' => $mem['id'],'comid'=>$param['comid'],'logintime' => $day])->find();
        if(!empty($record)){
            return admin_json(1,'该用户今天已登录',['token'=>$token]);
        }

        $result = Db::name('login_record_son')->insert(['memid' => $mem['id'],'comid'=>$param['comid'],'logintime' => $day]);
        if(!empty($result)){
            return admin_json(1,'获取成功',['token'=>$token]);
        }else{
            return admin_json(1,'获取成功',['token'=>$token]);
        }
    }
    /**
     * [edit  添加寺院记录]
     * @author [C。]
     * @return json
     */
    public function edit_readnum()
    {
        $param = input('param.');
        $model = new CompanyModel;
        try{
            $model->edit_readnum(['id'=>$param['id']]);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '失败'.$e->getMessage());
        }
        return admin_json(1, '成功');
    }
    /**
     * [getmodules 获取模块]
     * @param $param['states'] 1回复 0清空
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getModules()
    {
        $param = input('param.');
        $model = new CompanyModel;
        try{
            $data = $model->findData($param['id'],'id','modules');
            if(empty($data['modules'])){
                $moren = config('modules');
                $data = $moren;
            }else{
                $data = unserialize($data['modules']);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '失败'.$e->getMessage());
        }
        return admin_json(1, '成功',$data);
    }
    /**
     * [getMusic 获取音乐]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getMusic()
    {
        $param = input('param.');
        $model = new CompanyModel;
        try{
            $data = $model->findData($param['id'],'id','bj_music');
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '失败'.$e->getMessage());
        }
        return admin_json(1, '成功',$data);
    }
    /**
     * [getContent  根据id获取古刹内容]
     * @param
     * @author [C。]
     * @return json
     */
    public function getNotice()
    {
        $model = new CompanyModel;
        $param = input('param.');
        try{
            $company = $model->findData($param['id'],'id','notice');
            if(empty($company['notice'])){
                $company['notice'] = config('home.notice');
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$company['notice']);
    }
}